package com.zjxf.service.impl;

import com.zjxf.base.bean.po.UmsAdmin;
import com.zjxf.base.bean.vo.VoUmsAdmin;
import com.zjxf.base.common.OperationException;
import com.zjxf.base.common.SysConst;
import com.zjxf.repository.UmsAdminRepository;
import com.zjxf.service.UmsAdminService;
import com.zjxf.utils.Digests;
import com.zjxf.utils.Encodes;
import com.zjxf.utils.UserUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

/**
 * 管理员用户Impl
 *
 * @author ZhangWei
 * @date 2021/3/26/026 19:01
 */
@Service
@AllArgsConstructor
@Transactional(rollbackOn = RuntimeException.class)
public class UmsAdminServiceImpl implements UmsAdminService {

    private final UmsAdminRepository umsAdminRepository;

    @Override
    public Optional<UmsAdmin> findById(Long id) {
        return umsAdminRepository.findByIdAndDeleteState(id, SysConst.DeleteState.UN_DELETE_STATE.getCode());
    }

    @Override
    public Optional<UmsAdmin> findByUsernameAndDeleteState(String userName, Integer deleteState) {
        return umsAdminRepository.findByUsernameAndDeleteState(userName, deleteState);
    }

    @Override
    public void addOrUpdate(VoUmsAdmin.addOrUpdate voAdmin) throws OperationException {
        Optional<UmsAdmin> umsAdminOptionalByUserName = umsAdminRepository.findByUsernameAndDeleteState(voAdmin.getUsername(), SysConst.DeleteState.UN_DELETE_STATE.getCode());
        Optional<UmsAdmin> umsAdminOptionalById = umsAdminRepository.findByIdAndDeleteState(voAdmin.getId(), SysConst.DeleteState.UN_DELETE_STATE.getCode());
        if (umsAdminOptionalByUserName.isPresent()) {
            throw new OperationException("该用户名已存在，请重新输入");
        } else {
            if (umsAdminOptionalById.isPresent()) {
                UmsAdmin umsAdmin = umsAdminOptionalById.get();
                String salt = Encodes.encodeHex(Digests.generateSalt(Digests.SALT_SIZE));
                umsAdmin.setSalt(salt);
                String encryptPassword = UserUtils.getEncryptPassword(voAdmin.getPassword(), salt);
                umsAdmin.setPassword(encryptPassword);
                umsAdminRepository.save(umsAdmin);
            } else {
                UmsAdmin umsAdmin = new UmsAdmin();
                umsAdmin.setUsername(voAdmin.getUsername());
                String salt = Encodes.encodeHex(Digests.generateSalt(Digests.SALT_SIZE));
                umsAdmin.setSalt(salt);
                String encryptPassword = UserUtils.getEncryptPassword(voAdmin.getPassword(), salt);
                umsAdmin.setPassword(encryptPassword);
                umsAdminRepository.save(umsAdmin);
            }
        }
    }
}
